package com.yqg.education.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqg.education.entity.Menu;
import com.yqg.education.mapper.MenuMapper;
import com.yqg.education.service.IMenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * MenuServiceImpl 服务实现类
 * @author zxf
 * @since 2025-03-01
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> getTreeMenu(List<Menu> list) {
        List<Menu> treeMenu =
                list.stream()
                        .filter(i -> i.getPid() == null)
                        .map(i -> {
                            i.setMenuDtos(getChildren(i, list));
                            return i;
                        })
                        .collect(Collectors.toList());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(treeMenu);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return treeMenu;
    }

    private static List<Menu> getChildren(Menu node, List<Menu> list) {
        return list.stream()
                //当 参数的节点 == 循环的父节点（说明参数的节点 找到儿子了）
                .filter(i -> node.getId().equals(i.getPid()))
                //再次递归设置调用
                .map(i -> {
                    i.setMenuDtos(getChildren(i, list));
                    return i;
                })
                .collect(Collectors.toList());
    }
}
